﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LucyGrid;

namespace LucyDemo.Stream
{
	class StreamDemo: AbstractDemo
	{
		public override string Info()
		{
			return "Processes data input using the Grid";
		}

		IEnumerable<string> DataInput() { 
			string line = null;
			while(!string.IsNullOrEmpty(line = Console.ReadLine()))
				yield return line;
		}

		[Serializable]
		class InputData {
			public string line;
			public DateTime start;
		}
		[Serializable]
		class OutputData
		{
			public DateTime start;
			public DateTime process;
			public string words;
		}
		public override string Run(bool enableLocalProcessing)
		{
			Console.WriteLine("Write a line of text. The text will be send to the grid to count the words. A report about the process will be get back. Empty line to end");
			DataInput()
				.Select(line => new //InputData()
				{
					line = line,
					start = DateTime.Now
				})
				.AsParallelGrid(line => new //OutputData()
				{
					start = line.start,
					process = DateTime.Now,
					words = string.Join(",", line.line.Split(' ')
									.GroupBy(w => w)
									.Select(w => string.Format("{0}:{1}", w.Key, w.Count())))
				}, new GridSettings() { 
					EnableLocalProcessing = enableLocalProcessing
				})
			.All(o =>
			{
				var col = Console.ForegroundColor;
				Console.ForegroundColor = ConsoleColor.DarkGreen;
				Console.WriteLine("Start {0} End {1} Elapsed {2} ms. Info {3}",
					o.start.ToString("hh:mm:ss.fff"),
					DateTime.Now.ToString("hh:mm:ss.fff"),
					(DateTime.Now - o.start).TotalMilliseconds,
					o.words);
				Console.ForegroundColor = col;
				return true;
			});

			return "Done!";
		}
	}
}
